package com.lty.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.TimeUnit;

/***
 * 
* @ClassName: AIOServer 
* @Description: 异步io服务端
* @author Lau 
* @date 2017年7月9日 上午10:20:44 
*
 */
public class AIOServer {
	public AIOServer(int port) throws IOException{
		final AsynchronousServerSocketChannel listener = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(port));
		listener.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {

			public void completed(AsynchronousSocketChannel ch, Void vi) {
				listener.accept(null, this);//接收下一个连接
				handler(ch);
			}

			public void failed(Throwable exc, Void vi) {
				System.out.println("异步IO失败！");
			}
		
		});
	}
	
	//真正逻辑
	public void handler(AsynchronousSocketChannel ch){
		ByteBuffer byteBuffer = ByteBuffer.allocate(32);
		try {
			ch.read(byteBuffer).get();
		} catch (Exception e) {
			e.printStackTrace();
		}
		byteBuffer.flip();
		System.out.println("服务端接收：" + byteBuffer.get());
	}
	
	
	public static void main(String[] args) throws Exception {
		int port = 2017;
		AIOServer server = new AIOServer(port);
		System.out.println("服务端监听端口：" + port);
		TimeUnit.SECONDS.sleep(10);
	}
}
